package com.willren;

import android.os.Handler;
import android.os.Message;

/**
 * Execute some codes after some seconds
 */
public abstract class DelayRunner implements Runnable {
	
	private Handler handler;
	private long delayTime;
	private Thread thread;
	
	protected abstract void runningCode();
	
	protected DelayRunner() {
		handler = null;
		delayTime = 0;
		thread = null;
	}
	
	public void start(long second) {
		
		if(second > 0) {
			handler = new Handler() {
				
		    	@Override
		    	public void handleMessage(Message msg) {
					super.handleMessage(msg);
					
					runningCode();
		    	};
		    };
		    
		    delayTime = second;
		    
		    thread = new Thread(this);
		    if(null != thread) {
		    	thread.start();
		    }
		}
		else {
			runningCode();
		}
	}
	
	public void stop() {
		
		if(null != thread) {
			thread.interrupt();
	    }
	}
	
	@Override
	public void run() {
		
		try {
			Thread.sleep(delayTime * 1000);
			
			if(null != handler) {
				handler.sendEmptyMessage(0);
			}
		}
		catch(InterruptedException e) {
			Thread.currentThread().interrupt();
		}
	}
}
